﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;

namespace eComet
{
    public partial class Form1 : Form
    {

        public String installedDir = "";
        public Dictionary<String, String> paths = new Dictionary<string, string>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            installedDir = getInstalledDir();
            getPlugins();
            if (isECometRunning())
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }
        }

        public void getPlugins()
        {
            if (!installedDir.Equals(String.Empty))
            {
                int index = 0;
                object module = null;
                IECometPlugIn plugIn = null;
                String dir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\eComet\Plugins\";
                ECometConfig config;
                //MessageBox.Show("Paso1");
                Dictionary<String, uint> popups = new Dictionary<String, uint>();
                foreach (String archivo in Directory.GetFiles(dir))
                {
                    //String nomArch = archivo;
                    String nomArch = Path.GetFileName(archivo);
                    if (!nomArch.Equals("eCometPlugin.dll") && !nomArch.Equals("eCometPluginConfiguration.dll") && !nomArch.Equals("eCometPluginLoader.dll"))
                    {
                        string extension = Path.GetExtension(archivo).ToUpper();
                        if (extension.Equals(".DLL"))
                        {
                            //MessageBox.Show("Paso2 " + nomArch + " -> "+archivo);
                            module = ModuleManager.getInstance(archivo, "eComet.ECometPlugIn");
                            //MessageBox.Show("Pase el paso 2");
                            if (module != null)
                            {
                                bool esInstancia;
                                try
                                {
                                    plugIn = (IECometPlugIn)module;
                                    esInstancia = true;
                                }
                                catch
                                {
                                    esInstancia = false;
                                }
                                if (esInstancia)
                                {
                                    config = plugIn.Configuration();
                                    int indice = checkedListBox1.Items.Add(config.ApplicationName);
                                    paths.Add(indice.ToString(), archivo);
                                    checkedListBox1.SetItemChecked(indice, true);
                                }
                            }
                            else
                            {
                                //MessageBox.Show("Paso4 ");
                            }
                        }
                        else if (extension.Equals(".TOX"))
                        {
                            //MessageBox.Show("Paso2 " + nomArch + " -> "+archivo);
                            module = ModuleManager.getInstance(archivo, "eComet.ECometPlugIn");
                            //MessageBox.Show("Pase el paso 2");
                            if (module != null)
                            {
                                bool esInstancia;
                                try
                                {
                                    plugIn = (IECometPlugIn)module;
                                    esInstancia = true;
                                }
                                catch
                                {
                                    esInstancia = false;
                                }
                                if (esInstancia)
                                {
                                    config = plugIn.Configuration();
                                    int indice = checkedListBox1.Items.Add(config.ApplicationName);
                                    paths.Add(indice.ToString(), archivo);
                                    checkedListBox1.SetItemChecked(indice, false);
                                }
                            }
                            else
                            {
                                //MessageBox.Show("Paso4 ");
                            }
                        }
                    }
                    else
                    {
                        //MessageBox.Show("Si esta");
                    }
                }
                
            }
            else
            {
                MessageBox.Show("Please reinstall eComet");
            }
        }

        public String getInstalledDir()
        {
            String exit = "";
            try
            {
                RegistryKey root;
                RegistryKey rk;
                root = Registry.LocalMachine;
                rk = root.OpenSubKey("Software\\eComet", true);
                exit = rk.GetValue("Location").ToString();
                rk.Close();
            }
            catch
            {
 
            }
            return exit;
        }

        public bool isECometRunning()
        {
            bool exit = false;
            try
            {
                RegistryKey root;
                RegistryKey rk;
                root = Registry.ClassesRoot;
                rk = root.OpenSubKey("*\\shellex\\ContextMenuHandlers\\eComet", true);
                rk.Close();
                exit = true;
            }
            catch
            {

            }
            return exit;
        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = checkedListBox1.SelectedIndex;
            String dir = paths[index.ToString()];
            if (checkedListBox1.GetItemChecked(index))
            {
                if (Path.GetExtension(dir).ToUpper().Equals(".TOX"))
                {
                    String newFile = dir.Replace(".tox","");
                    File.Move(dir, newFile);
                    paths[index.ToString()] = newFile;
                }
            }
            else
            {
                if (Path.GetExtension(dir).ToUpper().Equals(".DLL"))
                {
                    String newFile = dir+".tox";
                    File.Move(dir, newFile);
                    paths[index.ToString()] = newFile;
                }
            }
        }

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //int index = checkedListBox1.SelectedIndex;
            //MessageBox.Show(paths[index.ToString()]);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            String dirNET = Environment.GetEnvironmentVariable("WinDir") + @"\Microsoft.NET\Framework\v2.0.50727\";
            String proceso = dirNET + "regasm.exe";
            String eCometPath = "\"" + installedDir + "eComet.dll" + "\"";
            if (checkBox1.Checked)
            {
                RunProcess(proceso, eCometPath);
            }
            else
            {
                RunProcess(proceso, "/unregister "+eCometPath);
            }
        }

        private int RunProcess(string command, string args)
        {
            var proc = new Process();
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo.FileName = command;
            if (args != String.Empty)
            {
                proc.StartInfo.Arguments = args;
            }

            try
            {
                proc.Start();
                proc.WaitForExit();
            }
            catch (Win32Exception e)
            {
                return -1;
            }

            //return proc.ExitCode;
            return 0;
        }
    }
}
